package com.pscsoft.lucene.demo;

import com.pscsoft.lucene.utils.DateUtils;
import com.pscsoft.lucene.utils.LuceneUtils;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.LongPoint;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.search.Query;
import org.junit.Test;

import java.io.BufferedReader;
import java.io.FileReader;

public class LuceneDemo {
    String log_data_path = "data/localhost_access_log.2020-10-19.txt";

    /**
     * 加载log数据并存储到lucene里面
     *
     * @throws Exception
     */

    @Test
    public void readLogDataSaveToDisk() throws Exception {

        IndexWriter indexWriter = LuceneUtils.getIndexWrite();
        BufferedReader br = new BufferedReader(new FileReader(log_data_path));
        String line = null;
        while ((line = br.readLine()) != null) {
            final String[] s = line.split(" ");
            final String time = s[3].replace("[", "");
            final long timestamp = DateUtils.string2Date(time).getTime();
            Document document = new Document();
            document.add(new TextField("value", line, Field.Store.YES));
            document.add(new LongPoint("searchTime", timestamp));

            indexWriter.addDocument(document);
        }
        LuceneUtils.indexWriterClose();
    }


    @Test
    public void searchDataByTime() throws Exception {
        searchDataByTime("searchTime", "19/Oct/2010:00:00:36", "19/Oct/2030:23:59:51");
    }

    /**
     * 根据开始时间和结束时间查询
     *
     * @param field     查询的时间字段
     * @param startTime 起始时间
     * @param endTime   结束时间
     * @throws Exception
     */
    public void searchDataByTime(String field, String startTime, String endTime) {

        Query query = LongPoint.newRangeQuery(field, DateUtils.string2Date(startTime).getTime(), DateUtils.string2Date(endTime).getTime());

        LuceneUtils.searchData(query);
    }

}
